//
//  AppDelegate.swift
//  ZNWeibo
//
//  Created by FunctionMaker on 2017/7/28.
//  Copyright © 2017年 FunctionMaker. All rights reserved.
//

import UIKit
import UserNotifications //iOS 10新增
import SVProgressHUD
import AFNetworking

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
//accessToken(访问令牌): 2.004GQL8GYTeVdDdf7b22858eI5c3cC
//homeUrl: https://api.weibo.com/2/statuses/home_timeline.json?access_token=2.004GQL8GYTeVdDdf7b22858eI5c3cC
//unreadUrl: https://api.weibo.com/2/remind/unread_count.json?access_token=2.004GQL8GYTeVdDdf7b22858eI5c3cC
//GET请求: 参数拼接在Url里，从?开始，格式为参数名=值
    
//OAuth2 授权：
//https://api.weibo.com/oauth2/authorize?client_id=3332219360&redirect_uri=http://baidu.com

//client_id: 3332219360
//App secret: 36f94d0efd9b4d5828040cceda86005a
//redirect_url: http://baidu.com

    
    
    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
        window = UIWindow()
        
        window?.backgroundColor = UIColor.white
        window?.rootViewController = ZNWBMainController()
        
        window?.makeKeyAndVisible()
        
        loadAppInfo()
        setupAdditions()
        
        return true
    }
}

extension AppDelegate {
    fileprivate func setupAdditions() {
        // 设置显示时间
        SVProgressHUD.setMinimumDismissTimeInterval(1.0)
        
        // 设置网络加载指示器
        AFNetworkActivityIndicatorManager.shared().isEnabled = true
        
        // 获取通知授权
        //iOS10及以上适用
        if #available(iOS 10.0, *) {
            UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .carPlay, .badge]) { (success, error) in
                print("请求" + (success ? "成功" : "失败" + "\(error?.localizedDescription ?? "")"))
            }
        } else {
            //通知授权：alert、sound、badgeNumber（应用图标上的）
            let settings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil);
            UIApplication.shared.registerUserNotificationSettings(settings)
        }
    }
}

extension AppDelegate {
    fileprivate func loadAppInfo() {
        //模拟应用设置网络加载
        DispatchQueue.global().async {
            let url = Bundle.main.url(forResource: "main.json", withExtension: nil)
            let data = NSData(contentsOf: url!)
            let docPath = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true)[0]
            let jsonPath = docPath + "/Preferences/main.json"
            
            data?.write(toFile: jsonPath, atomically: true)
            
            print(jsonPath)
        }
    }
}
